
import axios, { AxiosInstance, AxiosRequestConfig} from "axios";
// import qs from 'qs'
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";

// 请求计数
let loadingRequestCount = 0;
// loading实列
let loadingInstance: any = null;
const showLoading = () => {
  if (loadingRequestCount === 0) {
    // loadingInstance = Loading.service({ background: 'rgba(0, 0, 0, 0.4)', target: '.el-table' })
    loadingInstance = ElLoading.service({ background: "rgba(0, 0, 0, 0.4)" });
  }
  loadingRequestCount++;
};
const hideLoading = () => {
  if (loadingRequestCount <= 0) return;
  loadingRequestCount--;
  if (loadingRequestCount === 0) {
    setTimeout(() => {
      loadingInstance.close();
    }, 50);
  }
};

const config = {
  baseURL: 'http://120.24.224.201:1024',
  timeout: 1000 * 60,
  responseType: "json",
};

class RequestHttp {
  service: AxiosInstance;
  public constructor(config) {
    // instantiation
    this.service = axios.create(config);

    this.service.interceptors.request.use((config) => {
      const user = useStore.user()
      // 给headers加上token
      if (user.token) {
        config.headers["x-access-token"] = user.token;
      }
      // 请求拦截进来调用显示loading效果
      if (config.loading) {
        showLoading();
      }
      return config;
    });

    this.service.interceptors.response.use(
      (response) => {
        // 响应拦截进来隐藏loading效果，此处采用延时处理是合并loading请求效果，避免多次请求loading关闭又开启
        if (response.config.loading) {
          setTimeout(() => {
            hideLoading();
          }, 200);
        }

        const res = response.data;
        if (response.data.code === 0) {
          if (response.config.msg) {
            ElMessage({
              message: res.msg || "操作成功！",
              type: res.msgLevel || "success",
              duration: 5 * 1000,
            });
          }
          return res.data;
        } else {
          if (res.code === 30007 || res.code === 30008) {
            // 清理登录数据
            const user = useStore.user()
            user.cleanUser();
            ElMessageBox.confirm("登录已过期，请重新登录！", "提示", {
              confirmButtonText: "确定",
              closeOnClickModal: false,
              closeOnPressEscape: false,
              showCancelButton: false,
              type: "error",
              showClose: false,
            }).then(() => {
              navigateTo('/', { external: true, redirectCode: 301 })
            });
            return Promise.reject(response);
          } else {
            ElMessage({
              grouping: true,
              message: res.msg || "Error",
              type: res.msgLevel || "error",
              duration: 5 * 1000,
            });
            return Promise.reject(response.data);
          }
        }
      },
      (error) => {
        setTimeout(() => {
          hideLoading();
        }, 200);
        if (error.response?.status === 401) {
          const user = useStore.user()
          if (user.token) {
            // 清理登录数据
            user.logout();
            ElMessageBox.confirm("登录已过期，请重新登录！", "提示", {
              confirmButtonText: "确定",
              closeOnClickModal: false,
              closeOnPressEscape: false,
              showCancelButton: false,
              type: "error",
              showClose: false,
            }).then(() => {
              navigateTo('/', { external: true, redirectCode: 301 })
            });
          }
          return false;
        }
        ElMessageBox({
          dangerouslyUseHTMLString: true,
          message: `<p>${error.message}<p><p>${error.response?.data.msg || ""}</p>`,
          type: "error",
        });
        return Promise.reject(error);
      }
    );
  }

  get(url, params, _object = {}) {
    return this.service.get(url, { params, ..._object });
  }
  post(url, params, _object = {}) {
    return this.service.post(url, params, _object);
  }
  put(url, params, _object = {}) {
    return this.service.put(url, params, _object);
  }
  delete(url, params?: any, _object = {}) {
    return this.service.delete(url, { params, ..._object });
  }
  download(url, params, _object = {}) {
    return this.service.post(url, params, { ..._object, responseType: "blob" });
  }
}

export default new RequestHttp(config);
